<template>
  <div class="box">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/page' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert type="warning" :closable="false">
        <template>
          <i class="el-icon-info">注意：只允许第三级分类设置相关数据的参数！</i>
        </template>
      </el-alert>
      <!-- 级联菜单 -->
      <div class="block">
        <span class="demonstration">选择商品分类</span>
        <!-- 级联菜单 -->
        <el-cascader
          style="width: 300px"
          v-model="goods_cat"
          :options="options"
          :props="{
            expandTrigger: 'hover',
            label: 'cat_name',
            value: 'cat_id',
            children: 'children',
          }"
          @change="handleChange"
        ></el-cascader>
      </div>
      <!-- 级联菜单 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="0">
          <el-button
            style="margin-bottom: 10px"
            type="primary"
            :disabled="disabled"
            @click="add1"
            >添加分类</el-button
          >
          <!-- 表哥 -->
          <el-table :data="tableData" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item>
                    <el-tag
                      v-for="(tag, i) in scope.row.attr_vals"
                      :key="tag.name"
                      closable
                      @close="handleClose(scope.row, i)"
                      v-show="tag != ''"
                    >
                      {{ tag }}
                    </el-tag>
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                      >+ New Tag</el-button
                    >
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"> </el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" @click="handleEdit(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 表哥 -->
        </el-tab-pane>

        <!-- 静态 -->
        <el-tab-pane label="静态参数" name="1">
          <el-button
            type="primary"
            style="margin-bottom: 10px"
            :disabled="disabled"
            @click="add2"
            >添加分类</el-button
          >
          <el-table :data="tableData" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item>
                    <el-tag
                      v-for="(tag, i) in scope.row.attr_vals"
                      :key="tag.name"
                      closable
                      @close="handleClose(scope.row, i)"
                      v-show="tag != ''"
                    >
                      {{ tag }}
                    </el-tag>
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                      >+ New Tag</el-button
                    >
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"> </el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" @click="handleEdit(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 模态框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="label" prop="attr_name">
          <el-input v-model="ruleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="show != 0" type="primary" @click="submit('ruleForm')"
          >立即修改</el-button
        >
        <el-button
          v-show="show == 0"
          type="primary"
          @click="submitForm('ruleForm')"
          >立即创建</el-button
        >
        <el-button @click="resetForm('ruleForm')">取消</el-button>
      </div>
    </el-dialog>
    <!-- 模态框 -->
  </div>
</template>

<script>
import {
  goods,
  categories,
  attributes,
  upload,
  goodsss,
  deletegoods,
  addA,
  attrId,
  deless,
  tagg,
} from '@/api/login.js'
export default {
  data() {
    return {
      options: [],
      goods_cat: '',
      activeName: '0',
      tableData: [],
      attr_id: 0, //分类id
      cartid: 0, //参数id
      disabled: true, //按钮的状态
      dialogFormVisible: false,
      show: 0,
      ruleForm: {
        attr_name: '',
        attr_sel: '',
        attr_vals: '',
      },
      rules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      title: '添加动态参数',
      label: '动态参数',
      // tag
      inputVisible: false,
      inputValue: '',
      // tag
    }
  },
  mounted() {
    categories().then((res) => {
      // console.log(res.data.data)
      this.options = res.data.data
    })
  },
  methods: {
    getlist(one) {
      attributes(this.attr_id, one).then((res) => {
        // console.log(res)
        if (res.data.meta.status == 200) {
          this.$message.success(res.data.meta.msg)
          this.disabled = false
          res.data.data.forEach((item) => {
            item.inputVisible = false
            item.inputValue = ''
            //转数组
            item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          })
          this.tableData = res.data.data
          // console.log(this.tableData)
        }
      })
    },
    handleChange(e) {
      this.attr_id = e[e.length - 1]
      this.show = 0
      // console.log(this.attr_id)
      if (this.label == '动态参数') {
        this.getlist('many')
      } else {
        this.getlist('only')
      }
    },
    // tab
    handleClick(e) {
      if (e.index == '0') {
        this.title = '添加动态参数'
        this.label = '动态参数'
        this.ruleForm.attr_name = ''
        attributes(this.attr_id, 'many').then((res) => {
          // console.log(res)
          if (res.data.meta.status == 200) {
            this.$message.success(res.data.meta.msg + '动态参数')
            this.tableData = res.data.data
            this.disabled = false
            this.getlist('many')
          }
        })
      } else {
        this.ruleForm.attr_name = ''
        this.title = '添加静态参数'
        this.label = '静态参数'
        attributes(this.attr_id, 'only').then((res) => {
          console.log(res)
          if (res.data.meta.status == 200) {
            this.$message.success(res.data.meta.msg + '静态参数')
            this.tableData = res.data.data
            this.disabled = false
            this.getlist('only')
          }
        })
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.label == '动态参数') {
            this.ruleForm.attr_sel = 'many'
            addA(this.attr_id, this.ruleForm).then((res) => {
              // console.log('动态', res)
              if (res.data.meta.status == 201) {
                this.dialogFormVisible = false
                this.$message.success(res.data.meta.msg)
                res.data.data.forEach((item) => {
                  item.inputVisible = false
                  item.inputValue = ''
                  //转数组
                  item.attr_vals = item.attr_vals
                    ? item.attr_vals.split(' ')
                    : []
                  this.ruleForm.attr_name = ''
                })
              }
            })
            this.getlist('only')
            this.ruleForm = {
              attr_name: '',
              attr_sel: '',
              attr_vals: '',
            }
          } else {
            this.ruleForm.attr_sel = 'only'
            addA(this.attr_id, this.ruleForm).then((res) => {
              if (res.data.meta.status == 201) {
                this.dialogFormVisible = false
                res.data.data.forEach((item) => {
                  item.inputVisible = false
                  item.inputValue = ''
                  //转数组
                  item.attr_vals = item.attr_vals
                    ? item.attr_vals.split(' ')
                    : []
                })
                this.$message.success(res.data.meta.msg)
                this.ruleForm.attr_name = ''
              }
            })
          }
          this.getlist('many')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    //修改
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.label == '动态参数') {
            this.ruleForm.attr_sel = 'many'
            attrId(this.attr_id, this.cartid, this.ruleForm).then((res) => {
              console.log('动态', res)
              if (res.data.meta.status == 200) {
                this.$message.success(res.data.meta.msg)
                res.data.data.forEach((item) => {
                  item.inputVisible = false
                  item.inputValue = ''
                  //转数组
                  item.attr_vals = item.attr_vals
                    ? item.attr_vals.split(' ')
                    : []
                })
                this.dialogFormVisible = false
                this.getlist('many')
              }
            })
          } else {
            this.ruleForm.attr_sel = 'only'
            attrId(this.attr_id, this.cartid, this.ruleForm).then((res) => {
              if (res.data.meta.status == 200) {
                this.$message.success(res.data.meta.msg)
                res.data.data.forEach((item) => {
                  item.inputVisible = false
                  item.inputValue = ''
                  //转数组
                  item.attr_vals = item.attr_vals
                    ? item.attr_vals.split(' ')
                    : []
                })
                this.dialogFormVisible = false
                this.getlist('only')
              }
            })
          }
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    // tag
    async handleInputConfirm(row) {
      console.log(row)
      if (row.inputValue == '') {
        row.inputVisible = false
        row.inputValue = ''
        return false
      }
      if (this.label == '动态参数') {
        console.log('223当前行信息', row)
        //  console.log('新增加的值',row.inputValue);
        let value = row.inputValue
        //失焦，提交接口 要分类id,参数id,参数名,提交字符串(原始的+新增的)
        let cateId = this.attr_id
        let attr_id = row.attr_id
        let attr_name = row.attr_name
        let attr_sel = 'many'
        row.attr_vals.push(value)
        row.attr_vals = Array.from(new Set(row.attr_vals))

        // let attr_vals=row.attr_vals+' '+value  //字符串拼接的，不能响应式更新

        row.inputVisible = false
        row.inputValue = ''
        const { data: res } = await tagg(
          cateId,
          attr_id,
          attr_name,
          attr_sel,
          row.attr_vals.join(' '),
        )
        // console.log('新增参数成功', res)
        if (res.meta.status === 200) {
          this.$message.success('新增参数成功')
        }
      } else {
        // console.log('223当前行信息', row)
        //  console.log('新增加的值',row.inputValue);
        let value = row.inputValue
        //失焦，提交接口 要分类id,参数id,参数名,提交字符串(原始的+新增的)
        let cateId = this.attr_id
        let attr_id = row.attr_id
        let attr_name = row.attr_name
        let attr_sel = 'only'
        row.attr_vals.push(value)
        // let attr_vals=row.attr_vals+' '+value  //字符串拼接的，不能响应式更新
        row.attr_vals = Array.from(new Set(row.attr_vals))
        row.inputVisible = false
        row.inputValue = ''
        const { data: res } = await tagg(
          cateId,
          attr_id,
          attr_name,
          attr_sel,
          row.attr_vals.join(' '),
        )
        console.log('新增参数成功', res)
        if (res.meta.status === 200) {
          this.$message.success('新增参数成功')
        }
      }
    },
    async handleClose(row, i) {
      row.attr_vals.splice(i, 1)
      if (this.label == '动态参数') {
        // console.log('223当前行信息', row)
        //  console.log('新增加的值',row.inputValue);
        let value = row.inputValue
        //失焦，提交接口 要分类id,参数id,参数名,提交字符串(原始的+新增的)
        let cateId = this.attr_id
        let attr_id = row.attr_id
        let attr_name = row.attr_name
        let attr_sel = 'many'
        row.attr_vals.push(value)
        // let attr_vals=row.attr_vals+' '+value  //字符串拼接的，不能响应式更新

        row.inputVisible = false
        row.inputValue = ''
        const { data: res } = await tagg(
          cateId,
          attr_id,
          attr_name,
          attr_sel,
          row.attr_vals.join(' '),
        )
        console.log('新增参数成功', res)
        if (res.meta.status === 200) {
          this.$message.success('新增参数成功')
        }
      } else {
        // console.log('223当前行信息', row)
        //  console.log('新增加的值',row.inputValue);
        let value = row.inputValue
        //失焦，提交接口 要分类id,参数id,参数名,提交字符串(原始的+新增的)
        let cateId = this.attr_id
        let attr_id = row.attr_id
        let attr_name = row.attr_name
        let attr_sel = 'only'
        row.attr_vals.push(value)
        // let attr_vals=row.attr_vals+' '+value  //字符串拼接的，不能响应式更新

        row.inputVisible = false
        row.inputValue = ''
        const { data: res } = await tagg(
          cateId,
          attr_id,
          attr_name,
          attr_sel,
          row.attr_vals.join(' '),
        )
        console.log('新增参数成功', res)
        if (res.meta.status === 200) {
          this.$message.success('新增参数成功')
        }
      }

      //删除时，走接口
      // this.handleInputConfirm(row)
    },
    // 点击按钮，展示文本输入框
    showInput(row) {
      // console.log('当前行信息', row)
      row.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.focus()
      })
    },
    add1() {
      this.dialogFormVisible = true
      this.show = 0
      this.getlist('many')
    },
    add2() {
      this.dialogFormVisible = true
      this.show = 0
      this.getlist('only')
    },
    //tag
    //编辑
    handleEdit(e) {
      // console.log(e)
      if (this.label == '动态参数') {
        this.dialogFormVisible = true
        this.title = '修改动态参数'
        this.label = '动态参数'
        this.ruleForm.attr_name = e.attr_name
        this.cartid = e.attr_id
        this.show = 1
        this.ruleForm.attr_vals = e.attr_vals.join(' ')
        console.log(this.ruleForm.attr_vals)
      } else {
        this.dialogFormVisible = true
        this.title = '修改静态参数'
        this.label = '静态参数'
        this.ruleForm.attr_name = e.attr_name
        this.cartid = e.attr_id
        this.show = 1
        this.ruleForm.attr_vals = e.attr_vals.join(' ')
      }
    },
    // 删除
    handleDelete(e) {
      // console.log('删除', e)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          if (this.label == '动态参数') {
            deless(this.attr_id, e.attr_id).then((res) => {
              this.$message({
                type: 'success',
                message: res.data.meta.msg,
              })
              this.getlist('many')
            })
          } else {
            deless(this.attr_id, e.attr_id).then((res) => {
              this.$message({
                type: 'success',
                message: res.data.meta.msg,
              })
              this.getlist('only')
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
  },
  computed: {},
  watch: {},
}
</script>

<style scoped lang="scss">
.box {
  padding: 20px;
  .box-card {
    margin-top: 20px;
  }
  .block {
    margin: 20px 0px;
    span {
      margin-right: 18px;
    }
  }
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
